/* eslint-disable no-undef */
/* eslint-disable new-cap */
/* eslint-disable no-new */
/**
 * vue手势指令
 * @param {*} element  // 指令绑定dom
 * @param {object} binding  // 指令传递参数
 * @param {string} type     // 指令类型
 */

const loadTypes = ['imgload']

class vueLoad {
  constructor(element, binding, type) {
    this.element = element
    this.binding = binding
    loadTypes.forEach(key => {
      if (type === key) {
        this[key]()
      }
    })
  }
  // 图片加载指令
  imgload() {
    let color = Math.floor(Math.random() * 1000000)
    this.element.style.backgroundColor = '#' + color// 设置随机的背景颜色
    let img = new Image()
    img.src = this.binding.value // 获得传给指令的值
    img.onload = () => {
      // 通过改变背景图片来实现图片显示与隐藏
      this.element.style.backgroundImage = 'url(' + this.binding.value + ')'
    }
  }
}

// 注册自定义指令
const Load = {}
Load.install = (Vue, optinons) => {
  loadTypes.forEach(key => {
    Vue.directive(key, {
      inserted: function(ele, binding) {
        new vueLoad(ele, binding, key)
      }
    })
  })
}

export default Load
